package com.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.mall.common.dto.SkuEsModel;
import com.mall.search.config.ESConfig;
import com.mall.search.constant.EsConstant;
import com.mall.search.service.ElasticsearchService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 谢君臣
 * @Date: 2022/7/31-9:13
 * @version: 1.0
 * @function:
 */
@Service
@Slf4j
public class ElasticsearchServiceImpl implements ElasticsearchService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    @SneakyThrows
    @Override
    public boolean productUp(List<SkuEsModel> skuEsModelList) {

        // 简历索引
        BulkRequest request = new BulkRequest(EsConstant.PRODUCT_INDEX);
        skuEsModelList.forEach(item->{
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(item.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
            request.add(indexRequest);
        });
        BulkResponse response = restHighLevelClient.bulk(request, ESConfig.COMMON_OPTIONS);
        List<String> collect = Arrays.stream(response.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        if (response.hasFailures())
            // todo 错误处理
            log.error("商品上架异常：{}",collect);
        return response.hasFailures();
    }
}
